
interface ShopifyConfig {
  shopDomain: string;
  accessToken: string;
}

export const getShopifyProducts = async (config: ShopifyConfig) => {
  const response = await fetch(`https://${config.shopDomain}/admin/api/2024-01/products.json`, {
    headers: {
      'X-Shopify-Access-Token': config.accessToken,
    },
  });
  
  if (!response.ok) {
    throw new Error('Failed to fetch Shopify products');
  }
  
  const data = await response.json();
  return data.products;
};

export const saveDesignToShopify = async (designData: any, config: ShopifyConfig) => {
  const response = await fetch(`https://${config.shopDomain}/admin/api/2024-01/products.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Access-Token': config.accessToken,
    },
    body: JSON.stringify({
      product: designData
    }),
  });

  if (!response.ok) {
    throw new Error('Failed to save design to Shopify');
  }

  return response.json();
};

export const updateShopifyProductImage = async (productId: string, imageId: string, imageData: string, config: ShopifyConfig) => {
  const response = await fetch(`https://${config.shopDomain}/admin/api/2024-01/products/${productId}/images/${imageId}.json`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Access-Token': config.accessToken,
    },
    body: JSON.stringify({
      image: {
        attachment: imageData,
        filename: `design-${Date.now()}.png`
      }
    }),
  });

  if (!response.ok) {
    throw new Error('Failed to update Shopify product image');
  }

  return response.json();
};

export const authenticate = async (config: ShopifyConfig) => {
  const response = await fetch(`https://${config.shopDomain}/admin/api/2024-01/products.json`, {
    headers: {
      'X-Shopify-Access-Token': config.accessToken,
    },
  });
  
  if (!response.ok) {
    throw new Error('Failed to fetch Shopify products');
  }
  
  const data = await response.json();
  return data.products;
};